package storage.tx;

import server.starDB;
import storage.buffer.*;
import storage.file.Block;

import java.util.*;

class BufferList {
   private Map<Block,Buffer> buffers = new HashMap<Block,Buffer>();
   private List<Block> pins = new ArrayList<Block>();
   private BufferMgr bufferMgr = starDB.bufferMgr();
   
   
   Buffer getBuffer(Block blk) {
      return buffers.get(blk);
   }
   
   
   void pin(Block blk) {
      Buffer buff = bufferMgr.pin(blk);
      buffers.put(blk, buff);
      pins.add(blk);
   }
   
   
   Block pinNew(String filename, PageFormatter fmtr) {
      Buffer buff = bufferMgr.pinNew(filename, fmtr);
      Block blk = buff.block();
      buffers.put(blk, buff);
      pins.add(blk);
      return blk;
   }
   
   
   void unpin(Block blk) {
      Buffer buff = buffers.get(blk);
      bufferMgr.unpin(buff);
      pins.remove(blk);
      if (!pins.contains(blk))
         buffers.remove(blk);
   }
   
   
   void unpinAll() {
      for (Block blk : pins) {
         Buffer buff = buffers.get(blk);
         bufferMgr.unpin(buff);
      }
      buffers.clear();
      pins.clear();
   }
}